layui.define(['layer', 'form', 'table', 'jquery', 'laydate'],
    function (exports) {
      var $ = layui.$,
          form = layui.form,
          layer = layui.layer,
          laydate = layui.laydate,
          table = layui.table,
          currPageIndex = 1;

      var works = {
        render: function () {
          laydate.render({
            elem: '#createTime',
            range: true,//指定元素
            done: function (value, date, endDate) {
              $('input[name="startDate"]').val(date.year + "-" + date.month
                  + "-" + date.date + " 00:00:00");
              $('input[name="endDate"]').val(endDate.year + "-" + endDate.month
                  + "-" + endDate.date + " 23:59:59");
            }
          });

          $.get('/admin/works/getCategoryList', function (result) {
            $.each(result, function (index, category) {
              var option = ' <option value="' + category.catId + '">'
                  + category.catName + '</option>'
              $('#category_select').append(option);
            })
            form.render('select');
          }, 'json');

          $.get('/admin/works/getWorksProcessDetail', function (result) {
            for (var processEnum in result) {
              var option = ' <option value="' + processEnum + '">'
                  + result[processEnum] + '</option>'
              $('#process_select').append(option);
            }
            form.render('select');
          }, 'json');

          table.init('worksFilter', {
            done: function (res, curr, count) {
              currPageIndex = curr;
            }
          })

          table.on('sort(worksFilter)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            console.log(obj.field); //当前排序的字段名
            console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
            var Order = {},
                field = obj.field,
                direction = obj.type == null ? obj.type
                    : obj.type.toUpperCase();
            Order.sort = field + "," + direction;
            works.reloadTable(currPageIndex, Order, obj);
          });
        },

        bindEvent: function () {

          form.on('checkbox(otherProduct)', function (data) {
            if (data.elem.checked) {
              var worksId = data.value;
              $.post('/admin/works/updateWorksType', {id: worksId},
                  function (result) {

                  })
            }
          });

          //查看按钮点击事件
          $("#btn-query").click(function () {
            works.reloadTable(1)
          });

          $("#btn-pass").click(function () {

            var checkStatus = table.checkStatus('worksTable'),
                data = checkStatus.data,
                length = data.length;
            if (length == 0) {
              layer.msg('请至少选择一行数据');
            }
            layer.confirm('确定要审核通过?', {icon: 3, title: '提示'}, function (index) {
              layer.close(index);
              var loadingIndex = layer.load(),
                  passedCount = 0,
                  message = '';
              for (var index in data) {
                var id = data[index].id;
                $.post("/admin/works/pass", {id: id}, function (result) {
                  passedCount++;
                  if (!result.success) {
                    message += result.message + '</br>';
                  }
                  if (passedCount == length) {
                    if (message != '') {
                      layer.msg(message);
                    } else {
                      layer.msg('审核成功');
                    }
                    layer.close(loadingIndex);
                    var pageIndex = currPageIndex;
                    works.reloadTable(pageIndex);
                  }

                }, 'json')
              }
            })

          })

          $("#btn-refuse").click(function () {

            var checkStatus = table.checkStatus('worksTable'),
                data = checkStatus.data,
                worksId = [],
                length = data.length;
            if (length == 0) {
              layer.msg('请至少选择一行数据');
              return false;
            }

            for (var index in data) {
              worksId.push(data[index].id);
            }
            $('#refuseReason textarea').val('');
            layer.open({
              type: 1 //Page层类型
              , area: ['500px', '300px']
              , shade: false
              , title: false
              , anim: 1 //0-6的动画形式，-1不开启
              , content: $('#refuseReason')
              , btn: ['确定', '取消']
              , yes: function (index, layero) {
                var loadingIndex = layer.load();
                var refuseReason = layero.find('textarea').val();
                var param = {};
                param.ids = worksId;
                param.refuseReason = refuseReason;
                $.ajax({
                  type: 'post',
                  url: '/admin/works/batchRefuse',
                  data: JSON.stringify(param),
                  contentType: 'application/json',
                  dataType: 'json',
                  success: function (result) {
                    if (result.success) {
                      layer.msg('操作成功');
                    } else {
                      layer.msg(result.message);
                    }
                    layer.closeAll();
                    var pageIndex = currPageIndex;
                    works.reloadTable(pageIndex);
                  }
                })
              }
              , btn2: function (index, layero) {
                layero.find('textarea').val('');
                layer.close(index);
              }
            });

          })

          $(document).on('change', 'input[name="score"]', function () {
            var id = $(this).data('id'),
                score = $(this).val();
            $.post('/admin/works/updateScore', {id: id, score: score},
                function (result) {

                })
          })

          $(document).on('change', '#keywords', function () {
            var keywords = $(this).val(),
                id = $(this).data('id');
            console.log(keywords);
            $.post('/admin/works/updateKeyWords', {id: id, keywords: keywords},
                function (result) {
                })
          })

          //工具条事件
          table.on('tool(worksFilter)', function (obj) {
            var layEvent = obj.event,
                $tr = obj.tr,
                score = $tr.find('input[name="score"]').val(),
                keywords = $tr.find('textarea').val(),
                id = obj.data.id,
                uses = $tr.find('select').val();
            if (layEvent == 'detail') {
              var url = '/admin/works/detail?id=' + id;
              layer.open({
                content: url, type: 2, title: '查看详情', shadeClose: true,
                shade: 0.5,
                area: ['100%', '100%'],
                fix: false,
                maxmin: false,
              })

            } else if (layEvent == 'pass') {
              layer.confirm('确定要审核通过?', {icon: 3, title: '提示'},
                  function (index) {
                    var loadingIndex = layer.load();
                    $.post("/admin/works/pass",
                        {id: id, keyworks: keywords, score: score, uses: uses},
                        function (result) {
                          layer.close(loadingIndex);
                          if (result.success) {
                            layer.msg("审核成功！")
                          } else {
                            layer.msg("审核失败，失败原因：" + result.message);
                          }
                          var pageIndex = currPageIndex;
                          works.reloadTable(pageIndex);
                        }, 'json')

                    layer.close(index);
                  });

            } else if (layEvent == 'refuse') {

              layer.open({
                type: 1 //Page层类型
                , area: ['500px', '300px']
                , shade: false
                , title: false
                , anim: 1 //0-6的动画形式，-1不开启
                , content: $('#refuseReason')
                , btn: ['确定', '取消']
                , yes: function (index, layero) {
                  var loadingIndex = layer.load();
                  var refuseReason = layero.find('textarea').val();
                  $.post("/admin/works/refuse",
                      {id: id, refuseReason: refuseReason}, function (result) {
                        layer.close(loadingIndex);
                        if (result.success) {
                          layer.msg("审核成功！")
                        } else {
                          layer.msg("审核失败，失败原因：" + result.message);
                        }
                        layero.find('textarea').val('');
                        layer.close(index);
                        var pageIndex = currPageIndex;
                        works.reloadTable(pageIndex);
                      }, 'json')
                }
                , btn2: function (index, layero) {
                  layero.find('textarea').val('');
                  layer.close(index);
                }
              });
            } else if (layEvent == 'off') {
              layer.confirm('确定要下架该作品吗?', {icon: 3, title: '提示'},
                  function (index) {
                    var loadingIndex = layer.load();
                    $.get("/admin/works/offImage", {id: id}, function (result) {
                      layer.close(loadingIndex);
                      if (result.success) {
                        layer.msg("下架成功！")
                      }
                      var pageIndex = currPageIndex;
                      works.reloadTable(pageIndex);
                    }, 'json')
                    layer.close(index);
                  });
            }

          });
        },
        reloadTable: function (pageIndex, sort, obj) {
          var formJsonData = $('.layui-form').serializeJSON();
          $.extend(formJsonData, sort);
          table.reload('worksTable', {
            initSort: obj,
            where: formJsonData
            , page: {
              curr: pageIndex
            }
          });
        }

      }
      works.render();
      works.bindEvent();
      exports('works', {}); //注意，这里是模块输出的核心，模块名必须和use时的模块名一致
    });